<template>
  <div class="h-full">
    <div class="p-xl flex-between" style="margin-bottom: -2rem;">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange" style="flex: 0 0 auto;">
        <el-tab-pane label="首页" name="home"></el-tab-pane>
        <el-tab-pane label="收藏" name="favorite"></el-tab-pane>
      </el-tabs>
      <el-button type="primary" :icon="Plus" circle @click="goToCreate" />
    </div>

    <div v-loading="loading" class="p-sm">
      <div
        v-for="moment in moments"
        :key="moment.id"
        class="moment-item p-lg mb-sm cursor-pointer"
        @click="goToDetail(moment.id)"
      >
        <div class="flex-between mb-md">
          <div class="flex gap-md" style="align-items: center;">
            <span class="text-xs text-primary">{{ formatDate(moment.createdTime) }}</span>
            <span class="text-xs text-secondary">{{ getWeekday(moment.createdTime) }}</span>
            <span class="font-medium text-primary">{{ moment.title }}</span>
          </div>
          <el-icon class="icon-lg cursor-pointer favorite-icon" :class="{ active: moment.isFavorite }">
            <Star :filled="moment.isFavorite" />
          </el-icon>
        </div>
        <div class="moment-content">{{ moment.content }}</div>
      </div>

      <el-empty v-if="moments.length === 0 && !loading" description="暂无数据" />

      <div v-if="!hasMore && moments.length > 0" class="text-center p-lg text-secondary">
        已加载全部数据
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, inject, watch, onUnmounted, type Ref } from 'vue'
import { useRouter } from 'vue-router'
import { Star, Plus } from '@element-plus/icons-vue'
import { getMomentsList } from '../api'
import type { Moment } from '../types'
import { formatDate, getWeekday } from '@/utils/date'

const router = useRouter()

const moments = ref<Moment[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const activeTab = ref('home')
const hasMore = ref(true)

// 接收父组件传递的选中时间
const selectedTime = inject<Ref<string>>('selectedTime', ref(''))

const fetchMoments = async (append = false) => {
  if (loading.value || (append && !hasMore.value)) return

  loading.value = true
  try {
    const isFavorite = activeTab.value === 'favorite' ? true : undefined
    const page = append ? currentPage.value + 1 : 1
    const data = await getMomentsList(isFavorite, selectedTime.value || undefined, page, pageSize.value)

    if (append) {
      moments.value = [...moments.value, ...data.records]
    } else {
      moments.value = data.records
    }

    total.value = parseInt(data.total)
    currentPage.value = parseInt(data.current)
    pageSize.value = parseInt(data.size)

    // 判断是否还有更多数据
    hasMore.value = moments.value.length < total.value
  } catch (error) {
    console.error('获取 Moments 列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleScroll = (event: Event) => {
  const target = event.target as HTMLElement
  const scrollTop = target.scrollTop
  const scrollHeight = target.scrollHeight
  const clientHeight = target.clientHeight

  // 滚动到底部前 100px 时加载下一页
  if (scrollHeight - scrollTop - clientHeight < 100 && hasMore.value && !loading.value) {
    fetchMoments(true)
  }
}

const handleTabChange = () => {
  currentPage.value = 1
  hasMore.value = true
  fetchMoments()
}

const goToDetail = (id: string) => {
  router.push(`/moments/${id}`)
}

const goToCreate = () => {
  router.push('/moments/create')
}

// 监听选中时间变化，重新获取数据
watch(selectedTime, () => {
  currentPage.value = 1
  hasMore.value = true
  fetchMoments()
})

onMounted(() => {
  fetchMoments()

  // 获取父级滚动容器（center-panel）并监听滚动
  const scrollContainer = document.querySelector('.center-panel')
  if (scrollContainer) {
    scrollContainer.addEventListener('scroll', handleScroll)
  }
})

onUnmounted(() => {
  // 移除滚动监听
  const scrollContainer = document.querySelector('.center-panel')
  if (scrollContainer) {
    scrollContainer.removeEventListener('scroll', handleScroll)
  }
})
</script>

<style scoped>
.moment-item {
  background-color: #f8f8f8;
  border-radius: var(--radius-sm);
  transition: all 0.3s;
}

.moment-item:last-child {
  margin-bottom: 0 !important;
}

.favorite-icon.active {
  color: #f56c6c;
}

.moment-content {
  font-size: var(--font-size-base);
  color: var(--el-text-color-regular);
  line-height: 1.8;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: calc(1.8em * 5);
  overflow: hidden;
}
</style>
